<template>
    <div class="user-wrapper">
        <div class="user">

            <!--数据表格-->
            <el-table 
                ref="table"
                :data="tableData" 
                stripe 
                border >

                <el-table-column prop="id" label="id" width="80" sortable/>
                <el-table-column prop="username" label="username" width="160" />
                <el-table-column prop="password" label="password" width="160" />
                <el-table-column prop="name" label="name" width="160" />
                <el-table-column prop="intro" label="intro" width="320" />
                <el-table-column prop="sex" label="sex" width="60" />
                <el-table-column prop="birthday" label="birthday" width="160" />
                <el-table-column prop="user_status" label="user_status" width="120" >
                    <template #default="scope">
                        {{ scope.row.user_status === 1 ? '正常' : '冻结' }}
                    </template>
                </el-table-column>

                <el-table-column prop="role" label="角色" >
                    <template #default="scope">
                        <el-select
                            v-if="roles !== null"
                            placeholder="角色"
                            style="width: 240px"
                        >
                            <el-option
                                v-for="role in getRoleByRole_ids(scope.row.role_ids)" 
                                :key="role.id"
                                :label="role.name"
                                :value="role.id"
                                disabled
                            />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column fixed="right" label="Operations" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="openUpdateForm(scope.row)">修改</el-button>

                        <el-popconfirm title="确定要删除吗?" @confirm="deleteItem(scope.row.id)">
                            <template #reference>
                                <el-button link type="primary" size="small">删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>

            </el-table>

            <!--添加按钮-->
            <el-button 
                @click="addFormVisible = true"
                style="width: 100%; margin: 15px 0;">
                添加
            </el-button>

            <!--分页器-->
            <el-pagination
                v-model:currentPage="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[5, 10, 20, 30, 40, 50, 100, 200]"
                :total="total" 
                background
                layout="total, sizes, prev, pager, next, jumper"
                style="justify-content: center;" 
                @size-change="userByPage()"
                @current-change="userByPage()"
                @prev-click="userByPage()"
                @next-click="userByPage()" />

            <!--添加表单-->
            <el-dialog 
                v-model="addFormVisible"
                @close="handleClose"
                title="添加用户">

                <el-form 
                    @submit.prevent
                    :model="formData"
                    :rules="rules"
                    ref="addRuleFormRef"
                    label-width="120px">

                    <el-form-item label="username" prop="username">
                        <el-input v-model="formData.username" placeholder="用户名" />
                    </el-form-item>

                    <el-form-item label="password" prop="password">
                        <el-input
                            v-model="formData.password"
                            type="password"
                            show-password
                            placeholder="密码"
                        />
                    </el-form-item>

                    <el-form-item label="name" prop="name">
                        <el-input 
                            v-model="formData.name" 
                            placeholder="名称"
                        />
                    </el-form-item>

                    <el-form-item label="head_img" prop="head_img">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/head_img"
                            :show-file-list="false"
                            :on-success="uploadHeadeImgSuccess"
                        >
                            <img v-if="formData.head_img" :src="formData.head_img" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>

                    <el-form-item label="intro" prop="intro">
                        <el-input 
                            v-model="formData.intro" 
                            :rows="2"
                            type="textarea"
                            placeholder="个人简介"
                        />
                    </el-form-item>

                    <el-form-item label="sex" prop="sex">
                        <el-radio-group v-model="formData.sex">
                            <el-radio label="男" size="large">男</el-radio>
                            <el-radio label="女" size="large">女</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="birthday" prop="birthday">
                        <el-date-picker
                            v-model="formData.birthday"
                            type="date"
                            placeholder="出生日期"
                            size="default"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>

                    <el-form-item label="role_ids" prop="role_ids">
                        <el-select
                            v-model="formData.role_ids"
                            multiple
                            placeholder="角色"
                            style="width: 240px"
                        >
                            <el-option
                                v-for="role in roles"
                                :key="role.id"
                                :label="role.name"
                                :value="role.id"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="submit('POST', $refs.addRuleFormRef)">提交</el-button>
                    </el-form-item>

                </el-form>

            </el-dialog>

            <!--修改表单-->
            <el-dialog 
                v-model="updateFormVisible"
                @close="handleClose"
                title="修改用户">

                <el-form 
                    @submit.prevent
                    :model="formData"
                    :rules="rules"
                    ref="updateRuleFormRef"
                    label-width="120px">

                    <el-form-item label="id" prop="id" >
                        <el-input v-model="formData.id" disabled />
                    </el-form-item>

                    <el-form-item label="username" prop="username">
                        <el-input v-model="formData.username" placeholder="用户名" />
                    </el-form-item>

                    <el-form-item label="password" prop="password">
                        <el-input
                            v-model="formData.password"
                            type="password"
                            show-password
                            placeholder="密码"
                        />
                    </el-form-item>

                    <el-form-item label="name" prop="name">
                        <el-input v-model="formData.name" />
                    </el-form-item>

                    <el-form-item label="head_img" prop="head_img">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/head_img"
                            :show-file-list="false"
                            :on-success="uploadHeadeImgSuccess"
                        >
                            <img v-if="formData.head_img" :src="formData.head_img" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>

                    <el-form-item label="intro" prop="intro">
                        <el-input 
                            v-model="formData.intro" 
                            :rows="2"
                            type="textarea"
                            placeholder="个人简介"
                        />
                    </el-form-item>

                    <el-form-item label="sex" prop="sex">
                        <el-radio-group v-model="formData.sex">
                            <el-radio label="男" size="large">男</el-radio>
                            <el-radio label="女" size="large">女</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="birthday" prop="birthday">
                        <el-date-picker
                            v-model="formData.birthday"
                            type="date"
                            placeholder="出生日期"
                            size="default"
                            format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD"
                        />
                    </el-form-item>

                    <el-form-item label="role_ids" prop="role_ids">
                        <el-select
                            v-model="formData.role_ids"
                            multiple
                            placeholder="角色"
                            style="width: 240px"
                        >
                            <el-option
                                v-for="role in roles"
                                :key="role.id"
                                :label="role.name"
                                :value="role.id"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="submit('PUT', $refs.updateRuleFormRef)">提交</el-button>
                    </el-form-item>

                </el-form>

            </el-dialog>

        </div>
    </div>
</template>

<script>
import { Plus } from '@element-plus/icons-vue'
import { nextTick } from '@vue/runtime-core'
import { setUser, getUserByPage, getUserTotal } from '@/api/user.js'
import { getRoleByPage } from '@/api/role.js'

export default {
    name: 'user',
    components: {
        Plus
    },
    data() {
        return {
            currentPage: 1,
            pageSize: 10,
            total: 200,
            tableData: null,
            addFormVisible: false,
            updateFormVisible: false,
            formData: {
                id: null,
                username: null,
                password: null,
                head_img: null,
                name: null,
                intro: null,
                sex: '男',
                birthday: null,
                role_ids: null
            },
            rules: {
                username: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                    { max: 64, message: '最大长度为64', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                    { max: 64, message: '最大长度为64', trigger: 'blur' },
                ],
                name: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                    { max: 64, message: '最大长度为64', trigger: 'blur' },
                ],
                intro: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                    { max: 64, message: '最大长度为64', trigger: 'blur' },
                ],
                sex: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                    { max: 1, message: '最大长度为1', trigger: 'blur' },
                ],
                birthday: [
                    { required: true, message: '不能为空', trigger: 'blur' },
                ],
            },
            roles: null
        }
    },
    
    methods: {
        //关闭弹出表单
        handleClose () {
            for (const key of Reflect.ownKeys(this.formData)) {
                this.formData[key] = null
            }
            this.formData.sex = '男'
        },
        //打开更新表单
        openUpdateForm (row) {
            this.updateFormVisible = true

            //最简单的深拷贝
            this.formData = JSON.parse(JSON.stringify(row))
        },
        //根据user.role_ids返回对应的role数组
        getRoleByRole_ids (role_ids) {
            let role_arr = []
            role_ids.forEach(id => {
                for (const role of this.roles) {
                    if (id === role.id) {
                        role_arr.push(role)
                    }
                }
            })

            return role_arr
        },
        //头像上传成功回调
        uploadHeadeImgSuccess (res) {
            this.formData.head_img = res.data
        },

        //增改
        submit (method, formRef) {
            formRef.validate(async (valid, fields) => {
                if (valid) {
                    this.addFormVisible = false
                    this.updateFormVisible = false
                    let successMsg = method === 'POST' ? '添加成功' : '修改成功'

                    let result = await setUser(this.formData, method)
                    if (result instanceof Error) return ElMessage.error(result.message)

                    ElMessage.success(successMsg)
                    this.userByPage()
                }
            })
        },
        //删
        async deleteItem (id) {
            let result = await setUser({ id }, 'DELETE')
            if (result instanceof Error) return ElMessage.error(result.message)

            ElMessage.success('删除成功')
            this.userByPage()
        },
        //查
        async userByPage () {
            let result1 = await getUserByPage(this.currentPage, this.pageSize)
            if (result1 instanceof Error) return ElMessage.error(result1.message)

            let result2 = await getUserTotal()
            if (result2 instanceof Error) return ElMessage.error(result2.message)
            
            this.tableData = result1
            this.total = result2.total

            nextTick(() => {
                this.$refs.table.sort('id', 'ascending')
            })
        },
        async roleByPage () {
            let result = await getRoleByPage(1, 999)
            if (result instanceof Error) return ElMessage.error(result.message)

            this.roles = result
        },
    },
    
    mounted () {
        this.userByPage()
        this.roleByPage()
    }
}
</script>

<style lang="less" scoped>
.user{
    padding: 20px;
}
</style>

<style>
    .avatar-uploader .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }


    .avatar-uploader > .el-upload {
        border: 1px dashed #cacaca;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        transition: .2s;
    }

    .avatar-uploader > .el-upload:hover {
        border-color: #409eff;
    }

    .el-icon.avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        text-align: center;
    }
</style>